<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/7/18 16:26
 */

namespace module\user\controller;

use module\user\front\input\AvatarInput;
use module\user\front\input\BindInput;
use module\user\front\input\ProfileInput;
use module\user\front\input\UnbindInput;
use module\user\library\UserController;
use module\user\library\validate\CaptchaValidate;
use module\user\logic\ProfileLogic;
use mof\annotation\Inject;
use mof\ApiResponse;
use think\response\Json;

class Profile extends UserController
{
    #[Inject]
    protected ProfileLogic $logic;

    public function info(): Json
    {
        return ApiResponse::success($this->auth->getUser());
    }

    public function update(ProfileInput $profile): Json
    {
        $user = $this->logic->update($this->auth->getId(), $profile->data());
        return ApiResponse::success($user);
    }

    public function avatar(AvatarInput $avatar): Json
    {
        return ApiResponse::success(
            $this->logic->saveAvatar($this->auth->getUser(), $avatar)
        );
    }

    public function changeMobile(): Json
    {
        CaptchaValidate::register();

        $data = $this->request->withValidate([
            'mobile|新手机号' => 'require|mobile|unique:user,mobile',
            'captcha|验证码'  => 'require|captcha:change_mobile,mobile'
        ]);

        $mobile = $this->auth->getUser()->mobile;
        if ($mobile === $data['mobile']) {
            return ApiResponse::error('新手机号不能与当前手机号相同');
        }

        $this->logic->update($this->auth->getId(), ['mobile' => $data['mobile']]);
        //$this->auth->refresh();
        return ApiResponse::success();
    }

    public function changePassword(): Json
    {
        $user = $this->auth->getUser();

        CaptchaValidate::register();
        $data = $this->request->withValidate([
            'captcha|验证码'            => 'requireWithout:old_password|captcha:change_password,#' . $user->mobile,
            'old_password|旧密码'       => 'requireWithout:captcha',
            'new_password|新密码'       => 'require|min:5',
            'confirm_password|确认密码' => 'require|confirm:new_password'
        ])->post();

        if (empty($data['captcha']) && !password_verify($data['old_password'], $user->password)) {
            return ApiResponse::error('旧密码错误');
        }
        $this->logic->update($user->getId(), ['password' => $data['new_password']]);
        return ApiResponse::success();
    }

    public function bind(BindInput $input): Json
    {
        $this->logic->bind($this->auth->getUser(), $input->type, $input->account);
        return ApiResponse::success('ok');
    }

    public function unbind(UnbindInput $input): Json
    {
        $this->logic->unbind($this->auth->getUser(), $input->type, $input->account);
        return ApiResponse::success('ok');
    }
}